﻿(function($) {
    window.GoogleMapClass = function(options) {
        this.internal = {
            map: null,
            divTag: options.divTag,
            center: options.center,
            zoomLevel: options.zoom
        };
    };
    var image = '../../Content/Map/Images/YellowPin1LargeB.png';
    var drawingManager;
    var selectedShape;
    var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
    var selectedColor;
    var colorButtons = {};
    window.GoogleMapClass.prototype = {
        init: function(onLoadHandler) {
            var instance = this;
            google.maps.event.addDomListener(window, 'load', function() {
                var mapOptions = {
                    center: instance.internal.center,
                    zoom: instance.internal.zoomLevel,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        mapTypeIds : [
                            google.maps.MapTypeId.HYBRID,
                            google.maps.MapTypeId.ROADMAP,
                            google.maps.MapTypeId.SATELLITE,
                            google.maps.MapTypeId.TERRAIN
                        ]
                    }
                };

                instance.internal.Popup = new google.maps.InfoWindow();

                instance.internal.map = new google.maps.Map(document.getElementById(instance.internal.divTag),
                    mapOptions);

                var tilesloaded = google.maps.event.addListener(instance.internal.map, 'tilesloaded', function() {
                    onLoadHandler();
                    google.maps.event.removeListener(tilesloaded);
                });
            });
            //hide panel drawing result
            $("#panel").hide();
        },

        getMap: function() {
            return this.internal.map;
        },

        getCenterMap: function() {
            return this.internal.map.getCenter();
        },

        addFeature: function(f) {
            this.internal.map.data.add(f);
        },

        overrideFeatureStyle: function(feature, styleOption) {
            this.internal.map.data.overrideStyle(feature, styleOption);
        },

        //Show popup for map 
        showMapPopup: function(content, pos, callback) {
            //not pass the callback function
            if (typeof callback != "undefined")
            {
                google.maps.event.addListener(this.internal.Popup, "domready", function() {
                    callback();
                });
            }
            
            //close the previous popup
            this.internal.Popup.close();
            
            //Show and set content for the new popup
            this.internal.Popup.setContent(content);
            this.internal.Popup.setPosition(pos);
            this.internal.Popup.open(this.internal.map);
        },
        
        //Add custom control to map
        addControl : function(control, controlPosition) {
            control.index = 1;
            this.internal.map.controls[controlPosition].push(control);
        },
        
        //Drawing Tool
        DrawingTools: function() {
            drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.MARKER,
                drawingControl: true,
                drawingControlOptions: {
                    position: google.maps.ControlPosition.TOP_CENTER,
                    drawingModes: [
                        google.maps.drawing.OverlayType.MARKER,
                        google.maps.drawing.OverlayType.CIRCLE,
                        google.maps.drawing.OverlayType.POLYGON,
                        google.maps.drawing.OverlayType.POLYLINE,
                        google.maps.drawing.OverlayType.RECTANGLE
                    ]
                },
                //marker options
                markerOptions: {
                    icon: image,
                    draggable: true
                },
                //circle opetion
                circleOptions: {
                    fillColor: '#66FF99',
                    //fillOpacity: 1,
                    strokeWeight: 2,
                    clickable: true,
                    editable: true,
                    zIndex: 1
                },
                //polygon option
                polygonOptions:
                {
                    fillColor: '#66FF99',
                    //fillOpacity: 1,
                    strokeWeight: 2,
                    clickable: true,
                    editable: true,
                    zIndex: 1,
                    strokeColor: "#FF0000",
                    strokeOpacity: 0.8,
                },
                //rectangle option
                rectangleOptions:
                {
                    fillColor: '#66FF99',
                    //fillOpacity: 1,
                    strokeWeight: 2,
                    clickable: true,
                    editable: true,
                    zIndex: 1
                },
                polylineOptions:
                {
                    strokeWeight: 2,
                    clickable: true,
                    editable: true
                }
            });
            var map = this.internal.map;
            drawingManager.setMap(map);
            var result = null;
            var shapeType = google.maps.drawing.OverlayType;


            google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
                result =circle.getRadius() + ' (meters)';
                        $("#resultDrawing").val(result);
            });
            google.maps.event.addListener(drawingManager, 'mousedown', function(circle) {
                alert("ng");
                result =circle.getRadius() + ' (meters)';
                        $("#resultDrawing").val(result);
            });

            google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
                if (event.type != shapeType.MARKER) {
                    // Switch back to non-drawing mode after drawing a shape.
                    drawingManager.setDrawingMode(null);
//                        // To hide:
//                        drawingManager.setOptions({
//                            drawingControl: false
//                        });
                    // Add an event listener that selects the newly-drawn shape when the user
                    // mouses down on it.
                    var newShape = event.overlay;
                    newShape.type = event.type;
                    google.maps.event.addListener(newShape, 'click', function() {
                        window.GoogleMapClass.prototype.setSelection(newShape);
                    });
                    window.GoogleMapClass.prototype.setSelection(newShape);
                    //Show option result, color
                    $("#panel").show();
                } else {
                    result = event.overlay.getPosition();
                    $("#resultDrawing").val(result);
                }
            });
            // Clear the current selection when the drawing mode is changed, or when the
            // map is clicked.
            google.maps.event.addListener(drawingManager, 'drawingmode_changed', this.clearSelection);
            google.maps.event.addListener(map, 'click', this.clearSelection);
            google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', this.deleteSelectedShape);
            this.buildColorPalette();

            $("#option-button").click(function() {
                var $btn = $(this);
                var count = ($btn.data("click_count") || 0) + 1;
                $btn.data("click_count", count);
                if ((count % 2) != 0) {
                    $("#panel").show();
                    document.getElementById("option-button").title = "Ẩn thanh tùy chọn";
                } else {
                    $("#panel").hide();
                    document.getElementById("option-button").title = "Hiện thanh tùy chọn";
                }
            });
            $("#close-button").click(function() {
                $("#panel").hide();
            });
        },
        
        //Ex Drawing

        clearSelection: function() {
            if (selectedShape) {
                selectedShape.setEditable(false);
                selectedShape = null;
            }
        },

        setSelection: function(shape) {
            window.GoogleMapClass.prototype.clearSelection();
            selectedShape = shape;
            shape.setEditable(true);
            window.GoogleMapClass.prototype.selectColor(shape.get('fillColor') || shape.get('strokeColor'));
        },

        deleteSelectedShape: function() {
            if (selectedShape) {
                selectedShape.setMap(null);
            }
            // To show:
            drawingManager.setOptions({
                drawingControl: true
            });
        },

        selectColor: function(color) {
            selectedColor = color;
            for (var i = 0; i < colors.length; ++i) {
                var currColor = colors[i];
                colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
            }

            // Retrieves the current options from the drawing manager and replaces the
            // stroke or fill color as appropriate.
            var polylineOptions = drawingManager.get('polylineOptions');
            polylineOptions.strokeColor = color;
            drawingManager.set('polylineOptions', polylineOptions);

            var rectangleOptions = drawingManager.get('rectangleOptions');
            rectangleOptions.fillColor = color;
            drawingManager.set('rectangleOptions', rectangleOptions);

            var circleOptions = drawingManager.get('circleOptions');
            circleOptions.fillColor = color;
            drawingManager.set('circleOptions', circleOptions);

            var polygonOptions = drawingManager.get('polygonOptions');
            polygonOptions.fillColor = color;
            drawingManager.set('polygonOptions', polygonOptions);
        },

        setSelectedShapeColor: function(color) {
            if (selectedShape) {
                if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
                    selectedShape.set('strokeColor', color);
                } else {
                    selectedShape.set('fillColor', color);
                }
            }
        },

        makeColorButton: function(color) {
            var button = document.createElement('span');
            button.className = 'color-button';
            button.style.backgroundColor = color;
            google.maps.event.addDomListener(button, 'click', function() {
                window.GoogleMapClass.prototype.selectColor(color);
                window.GoogleMapClass.prototype.setSelectedShapeColor(color);
            });

            return button;
        },

        buildColorPalette: function() {
            var colorPalette = document.getElementById('color-palette');
            for (var i = 0; i < colors.length; ++i) {
                var currColor = colors[i];
                var colorButton = window.GoogleMapClass.prototype.makeColorButton(currColor);
                colorPalette.appendChild(colorButton);
                colorButtons[currColor] = colorButton;
            }
            window.GoogleMapClass.prototype.selectColor(colors[0]);
        },
        
        //--Handle events on map
        
        //Handle click event on map
        handleClickOnDataLayer: function(callback) {
            var internalMap = this.internal.map;
            google.maps.event.addListener(internalMap.data, "click", function(evt) {
                callback(evt);
            });
        },
        
        //Handle the drag end event on map
        handleDragEndOnMap: function(callback) {
            google.maps.event.addListener(this.internal.map, "dragend", function(evt) {
                callback(evt);
            });
        }
    };

})(jQuery);